package com.bilibili.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.bilibili.entity.User;
import com.bilibili.entity.Video;
import com.bilibili.service.VideoService;
import com.bilibili.service.impl.VideoServiceImpl;

@WebServlet("/createCenter.do")
@MultipartConfig
public class CreateCenterServlet extends HttpServlet {
    VideoService vs = new VideoServiceImpl();
    Video video = new Video();

    // 视频保存路径（Windows路径需转义反斜杠）
    private static final String VIDEO_UPLOAD_PATH = "C:\\material\\video";
    private static final String VIDEO_TRUE_PATH = "/bilibili/material/video/";
    // 封面保存路径
    private static final String COVER_UPLOAD_PATH = "C:\\material\\img\\cover";
    private static final String COVER_TRUE_PATH = "/bilibili/material/img/cover/";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            // 处理视频文件
            Part videoPart = request.getPart("videoFile");
            String videoFileName = saveFile(videoPart, VIDEO_UPLOAD_PATH);
            String durationStr = request.getParameter("durationInSeconds");
            int durationInSeconds = 0;

            if (durationStr != null && !durationStr.isEmpty()) {
                try {
                    durationInSeconds = Integer.parseInt(durationStr);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
            // 处理封面文件
            Part coverPart = request.getPart("coverFile");
            String coverFileName = saveFile(coverPart, COVER_UPLOAD_PATH);

            // 获取其他表单数据（可选）
            String title = request.getParameter("videoTitle");
            String desc = request.getParameter("videoDesc");
            String category = request.getParameter("videoCategory");
            //在此处写分类判断
            video.setTitle(title);
            video.setDescription(desc);
            video.setCoverUrl(COVER_TRUE_PATH + coverFileName);
            video.setVideoUrl(VIDEO_TRUE_PATH + videoFileName);
            video.setCategoryId(1);
            video.setUploaderId(((User)request.getSession().getAttribute("loginUser")).getUserId());
            video.setDuration(durationInSeconds);
            vs.insertVideo(video); // 修正方法名大小写

            // 返回成功结果
            out.write("{\"status\":\"success\",\"videoFileName\":\"" + videoFileName +
                    "\",\"coverFileName\":\"" + coverFileName + "\"}");

        } catch (Exception e) {
            e.printStackTrace();
            out.write("{\"status\":\"error\",\"message\":\"" + e.getMessage() + "\"}");
        } finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    /**
     * 通用文件保存方法
     * @param part 文件部件
     * @param targetPath 目标保存路径
     * @return 保存后的文件名（含扩展名）
     */
    private String saveFile(Part part, String targetPath) throws IOException {
        if (part == null || part.getSize() == 0) return null;

        // 确保目标路径存在
        Path path = Paths.get(targetPath);
        if (!Files.exists(path)) {
            Files.createDirectories(path); // 创建多级目录
        }

        // 提取原始文件名（处理不同浏览器的路径格式）
        String originalFileName = getFileName(part);
        if (originalFileName == null || originalFileName.isEmpty()) {
            throw new IOException("文件名为空");
        }

        // 生成唯一文件名（避免重名）
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf('.'));
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

        // 拼接完整保存路径
        Path savePath = path.resolve(uniqueFileName);

        // 写入文件
        try (InputStream inputStream = part.getInputStream();
             OutputStream outputStream = new FileOutputStream(savePath.toFile())) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }

        return uniqueFileName;
    }

    /**
     * 从Part中提取文件名（处理Content-Disposition头）
     */
    private String getFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        if (contentDisposition != null) {
            String[] parts = contentDisposition.split(";");
            for (String partStr : parts) {
                partStr = partStr.trim();
                if (partStr.startsWith("filename=")) {
                    // 去除引号（如：filename="video.mp4"）
                    return partStr.substring(partStr.indexOf('=') + 1).replace("\"", "");
                }
            }
        }
        return null;
    }
}